package com.jia.together.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jia.together.entity.Permission;
import com.jia.together.entity.Permission;
import com.jia.together.mapper.PermissionMapper;
import com.jia.together.service.PermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限 服务实现类
 * </p>
 *
 * @author dujiajia
 * @since 2021-02-19
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Override
    public Map<String, Object> selectPageList(Long pageNum, Long pageSize) {

        Page<Permission> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("gmt_create");
        Page<Permission> resourcePage = baseMapper.selectPage(page, wrapper);
        List<Permission> records = resourcePage.getRecords();
        long total = resourcePage.getTotal();
        Map<String, Object> map = new HashMap<>();
        map.put("records", records);
        map.put("total", total);
        return map;

    }

    @Override
    public Map<String, Object> selectTree() {
        List<Permission> permissions = baseMapper.selectList(null);


        List<Permission> collect = permissions.stream().filter(permission -> {
            return permission.getPid().equals("0");
        }).map(menu->{
            menu.setChildren(getChildren(menu,permissions));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        System.out.println("collect================="+collect);
        Map<String, Object> finalMap = new HashMap<>();
        finalMap.put("records",collect);
        finalMap.put("total",collect.size());
        return finalMap;
    }

    public List<Permission> getChildren(Permission root,List<Permission> all){
        List<Permission> children = all.stream().filter(item -> {
            return item.getPid().equals(root.getId());
        }).map(current -> {
            current.setChildren(getChildren(current, all));
            return current;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }
}
